# -*- coding = utf-8 -*-
#@Time: 2021/7/3 17:58
#@Author: 卜白
#@File: view.py
#@Software: PyCharm

from flask import Blueprint, request, jsonify, session, current_app, make_response
from apps.fictions.models import Book
from apps.users.models import User

# url_prefix加链接关键参数，防止两个路由出现重复的\   ,url_prefix='/user'
fiction = Blueprint('fiction',__name__)

# @fiction.after_request
# def af_req(resp):  #解决跨域session丢失
#     resp = make_response(resp)
#     # resp.headers['Access-Control-Allow-Origin'] = '*'
#     resp.headers['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
#     resp.headers['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS'
#     # resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
#     resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
#     resp.headers['Access-Control-Allow-Credentials'] = 'true'
#
#     # resp.headers['X-Powered-By'] = '3.2.1'
#     resp.headers['Content-Type'] = 'application/json;charset=utf-8'
#     return resp

# 获取导航栏小说分类 接口
@fiction.route('/books_cates', methods=['GET'])
def get_books_cates():
    resData = {
        "status": 201,
        "data": [
            {"id": 0, "text": '首页', "url": '/'},
            {"id": 1, "text": '玄幻小说', "url": '/fiction/xuanhuan'},
            {"id": 2, "text": '修真小说', "url": '/fiction/xiuzhen'},
            {"id": 3, "text": '都市小说', "url": '/fiction/dushi'},
            {"id": 4, "text": '历史小说', "url": '/fiction/lishi'},
            {"id": 5, "text": '网游小说', "url": '/fiction/wangyou'},
            {"id": 6, "text": '科幻小说', "url": '/fiction/kehuan'},
            {"id": 7, "text": '言情小说', "url": '/fiction/yanqing'},
            {"id": 8, "text": '其他小说', "url": '/fiction/qita'},
            {"id": 9, "text": '我的书架', "url": '/bookself'},
            {"id": 10, "text": '小说书库', "url": '/library'},
        ],  # 数据位置，一般为数组
        "message": '对本次请求的说明'
    }
    return jsonify(resData)

# 获取前N本推荐小说 数据接口
@fiction.route('/get_cate_limit/<limitnum>', methods=['GET'])
def get_cate_limit(limitnum):
    book = Book()
    # 获取数据
    arr_limit_data = book.get_book_infos_limit(limitnum)
    if arr_limit_data:
        json_data = {
            "data": arr_limit_data,
            "status" : 200,
            "msg":  "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403",msg="获取数据失败！")

# 获取前六本完结更新最早的 数据接口
@fiction.route('/get_complete_limit', methods=['GET'])
def get_complete_limit():
    book = Book()
    # 获取前六本完本小说数据
    arr_limit_data = book.get_complete_book_limit()
    if arr_limit_data:
        json_data = {
            "data": arr_limit_data,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="获取数据失败！")

# 获取各类别小说 以更新时间降序排列 的数据接口
@fiction.route('/get_cates_data/<book_cate>', methods=['GET'])
def get_cates_data(book_cate):
    book = Book()
    arr_cates_data = book.get_cates_desc_limit(book_cate)
    if arr_cates_data:
        json_data = {
            "data": arr_cates_data,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="此分类数据获取失败！")

# 首页最近更新以及言情小说的 limit30 的数据接口
@fiction.route('/get_update_romance_limit', methods=['GET'])
def get_update_romance_limit():
    book = Book()
    arr_update_romance = book.get_update_romance()
    if arr_update_romance:
        json_data = {
            "data": arr_update_romance,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="获取数据失败！")

# fiction_cates分类小说栏目 前limit6条数据 接口
@fiction.route('/get_fiction_limitsix/<fiction_cate>', methods=["GET"])
def get_fiction_limitsix(fiction_cate):
    book = Book()
    arr_fiction_cate = book.get_fiction_cates_limit_six(fiction_cate)
    if arr_fiction_cate:
        json_data = {
            "data": arr_fiction_cate,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="412", msg="获取分类小说数据失败！")

# fiction_cates分类小说栏目 分页数据  pagenum当前页数  pagesize每页条数
@fiction.route('/get_fiction_pagination', methods=["GET"])
def get_fiction_pagination():
    book = Book()
    params = request.args   # 获取get请求的params数组
    fiction_cate = params['query']  # 查询的小说分类
    pagenum = int(params['pagenum'] )    # 当前页数
    pagesize = int(params['pagesize'])   # 当前条数
    arr_fiction_list = book.get_fiction_cate_pagination(fiction_cate, pagenum, pagesize)
    if arr_fiction_list:
        return jsonify(arr_fiction_list)
    else:
        return jsonify(status="403", msg="获取分类数据列表失败！")

# 好看的分类小说 limit  fiction_cate小说分类   pagesize条数
@fiction.route('/get_good_look_ficiton', methods=["GET"])
def get_good_look_ficiton():
    book = Book()
    params = request.args  # 获取get请求的params数组
    fiction_cate = params['query']  # 查询的小说分类
    pagesize = int(params['pagesize'])  # 当前条数
    arr_fiction_list = book.get_good_look_fiction(fiction_cate,pagesize)
    if arr_fiction_list:
        json_data = {
            "data": arr_fiction_list,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="获取分类数据列表失败！")

# 获取小说详情页 数据接口
@fiction.route('/get_book_detail/<book_id>', methods=["GET"])
def get_book_detail(book_id):
    book = Book()
    arr_book_infos = book.get_book_infos_by_book_id(book_id)
    if arr_book_infos:
        json_data = {
            "data": arr_book_infos,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="获取小说详情数据失败！")

# 获取小说详情页 推荐limit 10数据接口
@fiction.route('/get_book_detail_recom/<fiction_cate>', methods=["GET"])
def get_book_infos_recom(fiction_cate):
    book = Book()
    arr_book_info_recom = book.get_book_info_recom_limit(fiction_cate)
    if arr_book_info_recom:
        json_data = {
            "data": arr_book_info_recom,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="获取小说详情数据失败！")

# 获取小说详情页最新章节 前12章
@fiction.route('/get_book_detail_newest/<book_id>', methods=["GET"])
def get_book_detail_newest(book_id):
    book = Book()
    arr_book_info_newest = book.get_book_detail_newest_twelve(book_id)
    if arr_book_info_newest:
        json_data = {
            "book_newest": arr_book_info_newest,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="该小说书籍不存在！")
    
# 获取小说详情页全部章节
@fiction.route('/get_book_detail_all/<book_id>', methods=["GET"])
def get_book_detail_all(book_id):
    book = Book()
    arr_book_detail_all = book.get_book_detail_all_chapter(book_id)
    if arr_book_detail_all:
        json_data = {
            "book_all": arr_book_detail_all,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="403", msg="该小说书籍不存在！")

# 获取小说章节详情页内容
@fiction.route('/get_fiction_chapter_infos', methods=["GET"])
def get_fiction_chapter_infos():
    book = Book()
    params = request.args  # 获取get请求的params数组
    sort_id = params['sort_id']  # 章节id
    book_id = params['book_id']  # 小说id
    arr_fiction_content = book.get_fiction_chapter_content(sort_id,book_id)
    if arr_fiction_content:
        json_data = {
            "book_chapter": arr_fiction_content,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="404", msg="该小说章节不存在！")

# 获取上一章的 sort_id 接口
@fiction.route('/get_fiction_pre_chapter', methods=["GET"])
def get_fiction_pre_chapter():
    book = Book()
    params = request.args  # 获取get请求的params数组
    book_id = params['book_id']       # 小说id
    sort_id = params['sort_id']       # 章节id
    arr_fiction_list = book.get_before_cap_id(book_id, sort_id)
    if arr_fiction_list:
        json_data = {
            "data": arr_fiction_list,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="404", msg="上一章小说不存在！")

# 获取下一章的 sort_id 接口
@fiction.route('/get_fiction_next_chapter', methods=["GET"])
def get_fiction_next_chapter():
    book = Book()
    params = request.args  # 获取get请求的params数组
    book_id = params['book_id']       # 小说id
    sort_id = params['sort_id']       # 章节id
    arr_fiction_list = book.get_next_cap_id(book_id, sort_id)
    if arr_fiction_list:
        json_data = {
            "data": arr_fiction_list,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="404", msg="下一章小说不存在！")

# 搜索书籍或作者 数据接口
@fiction.route('/search_infos/<search_key>', methods=["GET"])
def search_infos(search_key):
    book = Book()
    # params = request.args  # 获取get请求的params数组
    search_key = '%' + search_key + '%'
    arr_search_list = book.search_infos_by_key(search_key)
    # print(arr_search_list)
    if arr_search_list:
        json_data = {
            "data": arr_search_list,
            "status": 200,
            "msg": "请求成功"
        }
        return jsonify(json_data)
    else:
        return jsonify(status="404", msg="未找到相关数据结果！")

# fiction_cates分类小说栏目 分页数据  pagenum当前页数  pagesize每页条数
@fiction.route('/get_library_pages', methods=["GET"])
def get_library_pages():
    book = Book()
    params = request.args   # 获取get请求的params数组
    pagenum = int(params['pagenum'] )    # 当前页数
    pagesize = int(params['pagesize'])   # 当前条数
    arr_fiction_list = book.get_library_pagination(pagenum, pagesize)
    if arr_fiction_list:
        return jsonify(arr_fiction_list)
    else:
        return jsonify(status=412, msg="获取书库数据列表失败！")

# 将书籍添加入用户书架
@fiction.route('/get_info_bookself', methods=["POST"])
def get_info_bookself():
    book = Book()
    # 从session中取出用户id
    user_id = session.get('uid')
    if request.method == 'POST':
        # 请求的json数据返回字典
        requ_dict = request.get_json()
        book_id = requ_dict.get('book_id')

        try:
            # 判断书籍是否存在于书架中
            book_condition = book.get_user_book(user_id,book_id)
        except Exception as e:
            current_app.logger.error(e)
        else:
            if book_condition is None:
                # 表示书架中不存在这本书，执行添加书籍操作
                add_condition = book.Add_book_self(user_id,book_id)
                if add_condition == 412:
                    return jsonify(status=412, msg="加入书架失败！")
                elif add_condition == 200:
                    return jsonify(status=200, msg="加入书架成功！")
            else:
                return jsonify(status=404, msg="书架存在该书籍！")

# fiction_cates分类小说栏目 分页数据  pagenum当前页数  pagesize每页条数
@fiction.route('/get_bookself_pages', methods=["GET"])
def get_bookself_pages():
    book = Book()
    user_id = session.get('uid')    # 用户id
    if user_id:
        params = request.args   # 获取get请求的params数组
        pagenum = int(params['pagenum'] )    # 当前页数
        pagesize = int(params['pagesize'])   # 当前条数
        arr_fiction_list = book.get_bookself_pagination(user_id, pagenum, pagesize)
        if arr_fiction_list:
            return jsonify(arr_fiction_list)
        else:
            return jsonify(status=412, msg="获取用户书架数据列表失败！")

    else:
        return jsonify(status=404, msg="用户不存在！")

# 删除用户书架中的书籍信息
@fiction.route('/delete_bookself_infos/<user_id>/<book_id>', methods=["DELETE"])
def delete_bookself_infos(user_id,book_id):
    book = Book()
    if request.method == 'DELETE':
        try:
            book_condition = book.delete_book_infos(user_id,book_id)
        except Exception as e:
            current_app.logger.error(e)
        else:
            if book_condition == 412:
                return jsonify(status=412, msg="移除书架失败！")
            elif book_condition == 200:
                return jsonify(status=200, msg="移除书架成功！")

